'''
Author: didiplus
Description: 
Date: 2025-08-21 16:11:36
LastEditors: didiplus
LastEditTime: 2025-08-21 16:11:37
FilePath: /WeChatBot/app/api/deps.py
Version: 1.0
'''
# api/deps.py
"""
Author: didiplus
Description: API依赖项
Date: 2025-08-20 22:38:23
LastEditors: didiplus
LastEditTime: 2025-08-20 22:38:24
FilePath: /WeChatBot/app/api/deps.py
Version: 1.0
"""
# api/deps.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from typing import Generator, Optional
import jwt
from jwt import PyJWTError

from core.database import get_db
from services.user import UserService
from schemas.user import TokenData
from core.settings import settings
from models.user import User

# 确保 tokenUrl 路径与实际登录接口一致
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")

def get_current_user(
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
) -> User:
    """
    获取当前用户依赖项
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    if not token:
        raise credentials_exception
    
    try:
        # 解码 JWT token
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        user_id: int = payload.get("user_id")
        if user_id is None:
            raise credentials_exception
        token_data = TokenData(user_id=user_id)
    except PyJWTError as e:
        print(f"Token decode error: {e}")  # 添加调试信息
        raise credentials_exception
    
    # 获取用户信息
    user_service = UserService(db)
    user = user_service.get_user_by_id(user_id=token_data.user_id)
    if user is None:
        raise credentials_exception
    
    return user

def get_current_active_user(
    current_user: User = Depends(get_current_user)
) -> User:
    """
    获取当前激活用户依赖项
    """
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="用户未激活")
    return current_user